<template>
  <div class="tree__wrap">
    
    <el-tree
        :lazy="lazy"
        highlight-current
        ref="tree"
        :empty-text="emptyText"
        :props="defaultProps"
        :node-key="nodeKey"
        :default-expanded-keys="defaultExpandedKeys"
        :key="updateKey"
        class="tree-box"
        @node-click="(data, node, nodes) => nodeClick(data, node, nodes)"
        :data="data"
        :load="loadNode"
    >
      <span
          class="custom-tree-node"
          :class="`level-${node.level}`"
          slot-scope="{ node, data }"
          v-if="data.name"
      >
        <div class="title">
          <svg-icon icon-class="ic_leibie1"/>
          <span class="active">{{ data[[defaultProps.label]] }}</span>
        </div>
       
      </span>
     
    </el-tree>
  </div>
</template>
<script>
  export default {
    props: {
      title: String,
      action: Boolean,
      lazy: {
        default: false,
        type: Boolean
      },
      rootNodeId: {
        default: null,
        type: [Number, String]
      },
      typeId: {
        default: null,
        type: [Number, String]
      },
      expandOnClickNode: {
        type: Boolean,
        default: false
      },
      level: {
        type: Number,
        default: 0
      },
      emptyText: {
        type: String,
        default: '暂无数据'
      },
      data: {
        default: null,
        type: Array
      },
      defaultProps: {
        type: Object,
        default: () => {
          return {
            children: "children",
            label: "label"
          };
        }
      },
      nodeKey: {
        type: String,
        default: 'id'
      },
      updateKey: {
        type: Number,
        default: null
      },
      defaultExpandedKeys: {
        type: Array,
        default: null
      },
      // selectNode: {
      //   default: (() => {
      //   }),
      //   type: Function
      // },
      loadNode: {
        default: (() => {
        }),
        type: Function
      }
    },
    data () {
      return {
        // data: [],
        treeInputKey: null,
        addKey: null,
        source: null,
        ellipsis: false,
        parentId: null,
        id: null,
        addLoading: false
      };
    },
    methods: {
      mores (ev) {
        const dropdown = ev.target.parentNode.childNodes[1];
        dropdown.style.display = 'none';
      },
      more (ev, style = 'block') {
        const dropdown = ev.target.parentNode.parentNode.childNodes[1];
        dropdown.style.display = style;
      },
      nodeClick (data, node, nodes) {
        this.deleteIcon();
        this.$emit("node-click", data, node, nodes);
      },
      deleteIcon () {
        this.$nextTick(() => {
          document.querySelectorAll(`.level-${this.level}`).forEach(item => {
            const el = this.$getPrevNode(item);
            if (el) el.parentNode.removeChild(el);
          });
        });
      },
      handleCommand (command) {
        switch (command.type) {
          case 'up':
            this.sort(1, command.node, command.data)
            break;
          case 'down':
            this.sort(0, command.node, command.data)
            break;
          case 'del':
            this.deleteItem( command.data,command.node)
            break
          default:
        }
      },
      async sort (upOrDown, node, data) {
        // console.log(ev)
        // this.more(ev, 'none');
        const res = await this.$store.dispatch(
          "category/fetchPostSelectChildNodesSortChange",
          {
            ...data,
            upOrDown
          }
        );
        if (!res) return false;
        const parent = node.parent;
        const children = parent.childNodes;
        const index = children.findIndex(d => d.data.id === data.id);
        let sortIndex = null;
        if (upOrDown === 1) {
          sortIndex = index - 1;
        } else {
          sortIndex = index + 1;
        }
        [children[sortIndex].data, children[index].data] = [
          children[index].data,
          children[sortIndex].data
        ];
        [children[sortIndex].childNodes, children[index].childNodes] = [
          children[index].childNodes,
          children[sortIndex].childNodes
        ];
        [children[sortIndex].data.sort, children[index].data.sort] = [children[index].data.sort, children[sortIndex].data.sort];
        this.$emit('handelSort', data, upOrDown);
      },
      checkOverflow (ev) {
        const el = ev.target;
        if (el.scrollWidth > el.clientWidth) return (this.ellipsis = true);
        return (this.ellipsis = true);
      },
      deleteItem (data, node) {
        // this.more(ev, 'none');
        this.$confirm(`您确定删除 ${data.name} 吗？`, "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(async () => {
          const res = await this.$store.dispatch(
            "category/fetchDeleteMenu",
            data
          );
          if (!res) return false;
          const parent = node.parent;
          const children = parent.childNodes;
          const index = children.findIndex(d => d.data.id === data.id);
          children.splice(index, 1);

          const parents = node.parent;
          const childrens = parents.data.children || parents.data;
          const n = childrens.findIndex(d => d.id === data.id);
          childrens.splice(n, 1);
          this.$emit('delete-item', data)
        }).catch(() => { })
      },
      modifyNodeInput (node, data) {
        this.id = data.id;
        this.treeInputKey = data.name;
        this.source = data.name;

        data.name = null;
        node.expanded = !node.expanded;

        setTimeout(() => {
          this.$nextTick(() => {
            this.$refs.addInput.focus();
          });
        }, 100);
      },
      async addTreeNode (keyWord, data, node) {
        this.addLoading = true;
        this.deleteIcon();
        if (!keyWord) {
          if (this.source) {
            data.name = this.source;
          } else {
            const parent = node.parent;
            const children = parent.childNodes;
            const index = children.findIndex(d => d.data.id === data.id);
            children.splice(index, 1);

            const parents = node.parent;
            const childrens = parents.data.children || parents.data;
            const n = childrens.findIndex(d => d.id === data.id);
            childrens.splice(n, 1);
          }
          this.clearInput(node);
          return false;
        }
        let res = null;
        if (keyWord !== this.source) {
          res = await this.$store.dispatch(
            `category/${
              this.id ? "fetchPostUpdateChildNode" : "fetchPostAddChildNode"
              }`,
            {
              parentId: this.parentId,
              id: this.id,
              name: keyWord,
              rootId: this.typeId
            }
          );
        }
        if (res) {
          data.id = this.id ? this.id : res.data.id;
          data.name = this.treeInputKey;
          if (res.data) {
            data.sort = res.data.sort;
            data.nodeType = res.data.nodeType;
            data.parentId = res.data.parentId;
            data.rootId = res.data.rootId;
            data._modify = true;
          }

          this.clearInput(node);
        } else {
          data.name = this.source;
          if (this.source) {
            this.clearInput(node);
            return false;
          }
          const parent = node.parent;
          const children = parent.childNodes;
          const index = children.findIndex(d => d.data.id === data.id);
          children.splice(index, 1);

          const parents = node.parent;
          const childrens = parents.data.children || parents.data;
          const n = childrens.findIndex(d => d.id === data.id);
          childrens.splice(n, 1);
          this.clearInput(node);
        }
        this.$emit('modify-item', data, keyWord)
      },
      clearInput (node) {
        if (this.source) node.expanded = !node.expanded;
        this.treeInputKey = null;
        this.source = null;
        this.parentId = null;
        this.id = null;
        this.addLoading = false;
      },
      // 添加节点
      addTreeNodeInput (data, parentId, node = null) {
        this.treeInputKey = "";
        this.deleteIcon();
        this.addKey = data.label;
        this.parentId = parentId; // 分类标识
        if (node) node.expanded = true;
        if (data.label === "parent") {
          this.$refs['tree'].append({
            children: []
          });
        } else {
          if (!data.children) data.children = [];
          if (data._modify) {
            data.children.push({
              children: []
            });
          } else {
            this.$refs.tree.append(
              {
                children: []
              },
              data
            );
          }
        }
        setTimeout(() => {
          this.$refs['addInput'].focus();
        });
      },
    }
  };
</script>

<style lang="scss" scoped>
  @import "~@/styles/mixin.scss";
  .tree__wrap {
    width: 100%;
    // height: 100%;
    background: #fff;

    .type--add {
      text-align: right;
      padding-right: 20px;

      i {
        cursor: pointer;

        &:hover {
          color: $--color-primary;
        }
      }
    }
    .tree-box{
      height: calc(100vh - 227px);
      padding-bottom: 10px;
      @include scrollBar;
      /*/deep/  .dropdown{*/
      /*  padding-right: 15px;*/
      /*}*/
    }
    /deep/ .el-tree {
      max-height: calc(100% - 58px);
      .el-tree-node > .el-tree-node__children {
        overflow: visible;
      }
      .el-tree-node__content {
        position: relative;

        .custom-tree-node {
          width: calc(100% - 24px);
          min-width: 60px;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 14px;
          padding-right: 8px;

          .title {
            @include textEllipsis;

            &.active {
              width: calc(100% - 62px);
            }
          }

          .svg-icon {
            margin-right: 10px;
            font-size: 26px;
            vertical-align: -0.3em;
          }

          .el-input,
          .el-input__inner {
            height: 30px;
          }

          .icon__wrap {
            position: relative;
            height: 26px;
            display: flex;
            align-items: center;
            opacity: 0;

            .icon {
              margin-right: 5px;
            }

            .dropdown {
              margin-left: 5px;
            }

            .dropdown-menu {
              &.active {
                display: block;
              }

              display: none;
              position: absolute;
              left: 0;
              top: 21px;
              transform-origin: center bottom;
              z-index: 999999999999;
              padding: 10px 0;
              background-color: #fff;
              border: 1px solid $--border-color-base;
              border-radius: 4px;
              box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

              .popper__arrow {
                top: -12px;
                left: 50%;
                margin-right: 3px;
                border-top-width: 0;
                border-bottom-color: $--border-color-base;
                border-width: 6px;
                filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
                position: absolute;
                display: block;
                width: 0;
                height: 0;
                border-color: transparent;
                border-style: solid;

                &::after {
                  content: " ";
                  border-width: 6px;
                  position: absolute;
                  display: block;
                  width: 0;
                  height: 0;
                  border-color: transparent;
                  border-style: solid;
                  top: 1px;
                  margin-left: -6px;
                  border-top-width: 0;
                  border-bottom-color: #fff;
                }
              }

              li {
                list-style: none;
                margin: 0;
                line-height: 27px;
                padding: 0 15px;
                font-size: 13px;
                color: #606266;
                cursor: pointer;
                outline: none;

                &:focus,
                &:not(.is-disabled):hover {
                  background-color: #ecf5ff;
                  color: #66b1ff;
                }
              }
            }
          }
        }
      }

      .el-tree-node__content:hover .icon__wrap {
        opacity: 1 !important;
      }
    }
  }
</style>
